#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#define SERVPORT 3333 //定义端口号
#define BACKLOG 10 //请求队列中允许的最大请求数
#define MAXDATASIZE 50 //数据长度

int main() {
    struct sockaddr_in server_sockaddr, client_sockaddr;
    int sin_size, recvbytes;
    int listen_socket_fd, client_socket_fd; 
    char buf[MAXDATASIZE];
	
    if((listen_socket_fd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        perror("创建 server socket 失败");
        exit(1);
    }

    printf("Socket success!,listen_socket_fd = %d\n", listen_socket_fd);

    server_sockaddr.sin_family = AF_INET;
    server_sockaddr.sin_port = htons(SERVPORT);
    server_sockaddr.sin_addr.s_addr = INADDR_ANY;
	
    if((bind(listen_socket_fd, (struct sockaddr *)&server_sockaddr, sizeof(struct sockaddr))) == -1) {
        perror("bind error");
        exit(-1);
    }

    printf("bind success!\n");
	
    if(listen(listen_socket_fd, BACKLOG) == -1) {
        perror("listen error");
        exit(1);
    }

    printf("listening ... \n");
	
    if((client_socket_fd = accept(listen_socket_fd, (struct sockaddr *) &client_sockaddr, &sin_size)) == -1) {
        perror("accept error");
        exit(1);
    }

    printf("accept success!\n");
	
	for (;;) {
    	if((recvbytes = read(client_socket_fd, buf, MAXDATASIZE)) == -1) {
        	perror("read error");
        	exit(1);
    	}
		
		// 收到数据大小为 0，说明收到的是 FIN 终止连接请求
		if (recvbytes == 0) break;		

    	printf("received a connection : %s\n", buf);
		// 清空 buf
		memset(buf, 0x00, sizeof(buf));

		// 模拟处理延迟，睡 10 秒
		sleep(10);
		
		// 给客户端发送消息
		write(client_socket_fd, "hello server", 13);
	}
	
	// 7. 关闭 socket
	close(client_socket_fd);
    close(listen_socket_fd);

}
